<template>
  <div id="" class="container">
    <div class="leftNaV">
      <ul>
        <li :class="{'active': index === leftNavIndex}" class="" v-for="(item,index) in leftNavData" :key="index"
            @click="goToRouter(index, item)">
          {{ item.name }}
        </li>
      </ul>
      <Corner></Corner>
    </div>
    <div class="rightContent">
      <div class="search">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-input class="p-frame" placeholder="请输入种质名称" v-model="searchForm.name" clearable/>
            <!--            <el-select filterable v-model="searchForm.registerSaveId" placeholder="请选择种质名称" class="p-frame" clearable>
                          <el-option v-for="item in registerPreservation" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>-->
          </el-form-item>
          <el-form-item>
            <el-input class="p-frame" placeholder="请输入植株编号" v-model="searchForm.number" clearable/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="upload" @click="query">查询</el-button>
            <el-button type="primary" class="upload" @click="showDialog('add')" v-if="addBtn">新增</el-button>
            <el-button type="primary" class="upload" @click="deleteBatch" v-if="deleteBtn">批量删除</el-button>
            <!-- <el-button type="primary" @click="importVisible = true" v-if="importBtn">导入</el-button>-->
            <el-dropdown @command="exportTmpVal" class="exportMenu" trigger="click" v-if="exportBtn">
              <el-button type="primary">
                导出<i class="el-icon-arrow-down el-icon--right"/>
              </el-button>
              <el-dropdown-menu slot="dropdown" style="background-color: rgb(21 120 176)">
                <el-dropdown-item :command="false">
                  选择
                </el-dropdown-item>
                <el-dropdown-item :command="true">
                  全部
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </div>
      <div class="forms">
        <el-table ref="multipleTable" border stripe :data="tableData" v-loading="loading" element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                  @select="handleSelect" @select-all="handleSelectAll" :max-height="635">
          <el-table-column align="center" type="selection" v-if="exportBtn"/>
          <el-table-column show-overflow-tooltip align="center" prop="createDate" label="调查时间" min-width="160"/>
          <el-table-column show-overflow-tooltip align="center" prop="number" label="植株编号" min-width="140"/>
          <el-table-column show-overflow-tooltip align="center" prop="name" label="种质名称" min-width="140"/>
          <el-table-column show-overflow-tooltip align="center" prop="type" label="种质分类" min-width="140"/>
          <el-table-column show-overflow-tooltip align="center" prop="oneName" label="保存库名称" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="twoName" label="保存区名称" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="threeName" label="树种分区" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="fourName" label="小区名称" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="createName" label="调查人" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="lon" label="经度" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="lat" label="纬度" min-width="100"/>
          <el-table-column show-overflow-tooltip align="center" prop="alt" label="海拔" min-width="100"/>
          <el-table-column align="center" v-for="(val, key) in dynamicField" :key="key" :label="val.name">
            <el-table-column align="center" v-for="(item, i) in val.items" :key="i" :prop="item.name"
                             :label="item.name" show-overflow-tooltip :min-width="getWidth(item.name)">
              <template slot-scope="scope">
                {{ scope.row[item.name] }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" fixed="right" class-name="operation">
            <template slot-scope="scope">
              <span @click="showDialog('read', scope.row)" class="pointer">查看</span>
              <span v-if="updateBtn" @click="showDialog('edit', scope.row)" class="pointer">
                <i class="line"></i>修改
              </span>
              <span v-if="deleteBtn" @click="deleteRow(scope.row)" class="pointer">
                <i class="line"></i>删除
              </span>
            </template>
          </el-table-column>
        </el-table>
        <div class="paging">
          <el-pagination :page-size="this.pageSize" :page-sizes="[10,20,50]" :total="tableDataTotalCount"
                         @current-change="handleCurrentChange" @size-change="handleSizeChange" background
                         layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </div>
      <el-dialog :close-on-click-modal="false" :visible.sync="this.dialogFormVisible"
                 :title="this.dialogFormTitle + templateName" custom-class="dialogs" :before-close="cancel">
        <el-form class="single_3column" labelPosition='left' :inline="true" label-width="140px" ref="rules"
                 :model="addForm">
          <div class="table-all"
               style="width: calc(100%);box-sizing: border-box;margin: 10px auto 20px auto;border: 1px solid #D3D3D3;">
            <el-collapse v-model="active" accordion>
              <el-collapse-item title="基本信息" name="1">
                <div class="qr-ul">
                  <div class="table-td2"><span style="color:#B22222">*</span>植株编号:</div>
                  <div class="table-td3">
                    <el-input class="td-input" :disabled="disable" v-model="addForm.number"/>
                  </div>
                  <div class="table-td2"><span style="color:#B22222">*</span>种质名称:</div>
                  <div class="table-td3">
                    <el-input v-model="addForm.name" @focus="showRegister" :disabled="disable"/>
                  </div>
                </div>
                <div class="qr-ul">
                  <div class="table-td2">种质分类:</div>
                  <div class="table-td3">
                    <el-select filterable v-model="addForm.type" placeholder="请选择" :disabled="disable">
                      <el-option v-for="(item, i) in typeOption" :key="i" :label="item" :value="item"/>
                    </el-select>
                  </div>
                  <div class="table-td2"><span style="color:#B22222">*</span>调查时间:</div>
                  <div class="table-td3">
                    <el-date-picker
                      :disabled="disable"
                      v-model="addForm.createDate"
                      type="datetime"
                      placeholder="选择日期时间">
                    </el-date-picker>
                  </div>
                </div>
                <div class="qr-ul">
                  <div class="table-td2"><span style="color:#B22222">*</span>保存库:</div>
                  <div class="table-td3">
                    <el-select filterable v-model="addForm.oneId" @change="selectedOne" clearable :disabled="disable">
                      <el-option v-for="item in oneData" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </div>
                  <div class="table-td2"><span style="color:#B22222">*</span>保存区:</div>
                  <div class="table-td3">
                    <el-select filterable v-model="addForm.twoId" @change="selectedTwo" clearable :disabled="disable">
                      <el-option v-for="item in twoData" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </div>
                </div>
                <div class="qr-ul">
                  <div class="table-td2"><span style="color:#B22222">*</span>树种分区:</div>
                  <div class="table-td3">
                    <el-select filterable v-model="addForm.threeId" @change="selectedThree" clearable :disabled="disable">
                      <el-option v-for="item in threeData" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </div>
                  <div class="table-td2"><span style="color:#B22222">*</span>小区:</div>
                  <div class="table-td3">
                    <el-select filterable v-model="addForm.fourId" clearable :disabled="disable">
                      <el-option v-for="item in fourData" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </div>
                </div>

                <div class="qr-ul">
                  <div class="table-td2">经度:</div>
                  <div class="table-td3">
                    <div class="td3-box">
                        <!-- <el-input class="td-input" :disabled="true" v-model="chilLon"/> -->
                        <LonLat ref="lonRef" @child-event="lonEvent"  v-if ="isReady" :msg-val="chilLon" :disabled="disable"/>
                    </div>
                  </div>

                  <div class="table-td2">纬度:</div>
                  <div class="table-td3">
                    <div class="td3-box">
                        <!-- <el-input class="td-input" :disabled="true" v-model="chilLat"/> -->
                        <LonLat ref="latRef" @child-event="latEvent" v-if ="isReady"  :msg-val="chilLat" :disabled="disable"/>
                    </div>
                    <!-- <el-input class="td-input" :disabled="disable" v-model="addForm.lat"/> -->
                  </div>
                  <div class="table-td2">海拔:</div>
                  <div class="table-td3">
                    <el-input class="td-input" :disabled="disable" v-model="addForm.alt"/>
                  </div>
                </div>

              </el-collapse-item>
              <el-collapse-item class="dynamic" :title="template.name" v-for="(template, index) in dynamicField"
                                :key="index" :name="(index + 2)">
                <div v-for="(item, i) in template.items" :key="i" class="qr-ul">
                  <div class="table-td2">{{ item.name }}:</div>
                  <div class="table-td3" v-if="item.type === 'input'">
                    <el-input class="td-input" :disabled="disable" v-model="dataJson[item.name]"/>
                  </div>
                  <div class="table-td3" v-else-if="item.type === 'number'">
                    <el-input-number :disabled="disable" v-model="dataJson[item.name]"/>
                  </div>
                  <div class="table-td3" v-else-if="item.type === 'select'">
                    <el-select filterable v-model="dataJson[item.name]" placeholder="请选择" :disabled="disable">
                      <el-option v-for="subItem in item.children" :key="subItem.id" :label="subItem.name"
                                 :value="subItem.name"/>
                    </el-select>
                  </div>
                  <div class="table-td3" v-else-if="item.type === 'upload'" style="text-align:center">
                    <a v-if="dialogFormType === 'read'" target="_blank" :href="fileServerUrl + dataJson[item.name]">
                      <span v-if="dataJson[item.name] && dataJson[item.name].length > 0">
                        {{ dataJson[item.name].substring(dataJson[item.name].lastIndexOf('/') + 1, dataJson[item.name].length) }}
                      </span>
                    </a>
                    <el-upload
                      v-else
                      class="upload-demo"
                      :action="uploadAction"
                      :multiple="false"
                      :limit="1"
                      :name="item.name"
                      :disabled="disable"
                      :file-list="setFileList(dataJson[item.name])"
                      :on-exceed="handleExceed"
                      :http-request="uploadFile">
                      <el-button size="small" type="primary">选取文件</el-button>
                    </el-upload>
                  </div>
                  <div class="table-td3" v-else-if="item.type === 'data'">
                    <el-date-picker
                      v-model="dataJson[item.name]"
                      type="datetime"
                      :disable="disable"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间">
                    </el-date-picker>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-if="dialogFormType == 'edit'" class="dialogBtn" type="primary" @click="saveResource">修 改
          </el-button>
          <el-button v-else-if="dialogFormType == 'add'" type="primary" @click="saveResource">保 存</el-button>
          <el-button type="primary" @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" :visible.sync="dialogQrCodeVisible" title="扫码查看详情" custom-class="dialogs"
                 width="420px">
        <canvas id="QRCode" style="margin: 0 auto" ref="qrCodeDiv"></canvas>
        <div class="dialog-footer" slot="footer">
          <el-button @click="dialogQrCodeVisible = false" class="dialogBtn" type="primary">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog :close-on-click-modal="false" title="保存登记列表" :visible.sync="registerVisible"
                 :before-close="cancelRegister">
        <div class="search">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input placeholder="种质名称" v-model="registerName" class="p-frame" clearable/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="upload" @click="registerPage">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="forms">
          <el-table border stripe class="tableLine" :data="registerData" @row-click="checkedTableRows">
            <el-table-column prop="name" show-overflow-tooltip label="种质名称" align="center"/>
            <el-table-column prop="fourName" show-overflow-tooltip label="小区" align="center"/>
            <el-table-column prop="threeName" show-overflow-tooltip label="树种分区" align="center"/>
            <el-table-column prop="twoName" show-overflow-tooltip label="物种保存区" align="center"/>
            <el-table-column prop="oneName" show-overflow-tooltip label="林木保存库" align="center"/>
          </el-table>
        </div>
        <div slot="footer" class="dialog-footer">
          <div class="paging">
            <el-pagination :page-sizes="[10]" :page-size="registerSize" :current-page="registerIndex"
                           :total="registerTotal" @current-change="registerPager" background
                           layout="total, sizes, prev, pager, next, jumper"/>
          </div>
        </div>
      </el-dialog>
      <!--      <el-dialog :title="'导入'+ templateName" :visible.sync="importVisible" class="import" width="30%" :close-on-click-modal="false">
              <div style="text-align: center">
                <el-upload drag :action="importAction" class="upload-demo" :show-file-list="false" :data="importData"
                           :headers="uploadHeader" :before-upload="beforeUpload" :on-success="handleSuccess">
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip">
                    只能上传xls/xlsx文件，
                    <el-button type="text" @click="downloadExcel">下载模板</el-button>
                  </div>
                </el-upload>
              </div>
            </el-dialog>-->
    </div>
  </div>
</template>

<script>
import templateApi from '../../../api/templateApi'
import resourceApi from '../../../api/resourceApi'
import Corner from '../../../components/corner'
import QRCode from 'qrcode'
import axios from 'axios'
import ResourceManageApi from '../../../api/ResourceManageApi'
import LonLat from '../../../components/LatLon'
Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
}

export default {
  name: 'manage',
  components: {
    Corner,
    LonLat
  },
  data () {
    return {
      oneData: [],
      twoData: [],
      threeData: [],
      fourData: [],
      loading: false,
      registerPreservation: [],
      fileDomain: process.env.SURVEY_DOMAIN + '/gr/resource/importExcel?templateId=' + this.templateId,
      dataError: '',
      upHeader: {
        token: `${window.localStorage.token}`
      },
      disable: false,
      templateId: null,
      templateName: null,
      leftNavData: [],
      leftNavIndex: 0,
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      tableData: [],
      active: '1',
      searchForm: {
        name: null,
        number: null,
        start: null,
        end: null,
        staffIds: []
      },
      addForm: {},
      dataJson: {},
      titleData: {
        'add': '新增',
        'edit': '修改',
        'read': '查看'
      },
      typeOption: ['群体（种源、林分）', '家系', '个体（优树、无性系）', '地方品种', '选育品种', '育种材料（优良林分、优树、半同胞家系、全同胞家系、杂交后代、无性系）'],
      dialogFormType: 'detail',
      dialogFormTitle: '',
      dialogFormVisible: false,
      dialogQrCodeVisible: false,
      dialogImportVisible: false,
      fileServerUrl: process.env.FILE_SERVER,
      uploadAction: process.env.SURVEY_DOMAIN + '/accessory/uploadFile',
      registerSaveIds: [],
      addBtn: false,
      updateBtn: false,
      deleteBtn: false,
      importBtn: false,
      exportBtn: false,
      registerIndex: 1,
      registerSize: 10,
      registerTotal: 0,
      registerData: [],
      registerName: null,
      registerVisible: false,
      importVisible: false,
      importAction: process.env.SURVEY_DOMAIN + '/gr/register/save/excelImport',
      importData: {
        templateId: this.templateId
      },
      uploadHeader: {
        token: `${window.localStorage.token}`
      },
      onlyId: [],
      dynamicField: [],
      chilLon:'',
      chilLat:'',
      isReady:false
    }
  },
  computed: {
    tableDataTotalCount () {
      return this.totalCount ? this.totalCount : 0
    }
  },
  created () {
    this.initBtn();
    this.getNavData();
    this.findRegisterPreservation();
  },
  methods: {
    //经度
    lonEvent(val){
      this.addForm.lon = val;
    },

    latEvent(val){
      this.addForm.lat = val;
    },

    getOne () {
      this.getModule('one').then(res => {
        this.oneData = res
      })
    },
    async getModule (module) {
      let result = []
      let res = await ResourceManageApi.getModule(module)
      if (res.data.message === 'success') {
        result = res.data.result
      }
      return result
    },
    async getChildren (data) {
      let result = []
      if (data) {
        let res = await ResourceManageApi.getChildren(data)
        if (res.data.message === 'success') {
          result = res.data.result
        }
      }
      return result
    },
    selectedOne (data) {
      this.twoData = []
      this.threeData = []
      this.fourData = []
      this.$set(this.addForm, 'twoId', null)
      this.$set(this.addForm, 'threeId', null)
      this.$set(this.addForm, 'fourId', null)
      if (data) {
        this.getChildren(data).then(res => {
          this.twoData = res
        })
      }
    },
    selectedTwo (data) {
      this.threeData = []
      this.fourData = []
      this.$set(this.addForm, 'threeId', null)
      this.$set(this.addForm, 'fourId', null)
      if (data) {
        this.getChildren(data).then(res => {
          this.threeData = res
        })
      }
    },
    selectedThree (data) {
      this.fourData = []
      this.$set(this.addForm, 'fourId', null)
      if (data) {
        this.getChildren(data).then(res => {
          this.fourData = res
        })
      }
    },
    findRegisterPreservation () {
      resourceApi.findRegisterPreservation({}).then((res) => {
        if (res.data.messageCode === '200' && res.data.result) {
          this.registerPreservation = res.data.result
        } else {
          this.registerPreservation = []
        }
      })
    },
    beforeFileUpload (file) {
      let filename = file.name
      let size = file.size / 1024 / 1024
      if (filename.lastIndexOf('.') > 0) {
        let filehz = filename.substring(filename.lastIndexOf('.') + 1)
        let standbyList = ['xls', 'xlsx']
        if (standbyList.indexOf(filehz) !== -1) {
          if (size < 100) {
            return true
          } else {
            this.$notify({
              title: '消息',
              message: ('上传文件不能超过100M'),
              position: 'bottom-right',
              showClose: false,
              type: 'warning'
            })
            return false
          }
        } else {
          this.$notify({
            title: '消息',
            message: ('上传失败，请上传xls, xlsx文件'),
            position: 'bottom-right',
            showClose: false,
            type: 'warning'
          })
          return false
        }
      } else {
        return true
      }
    },
    handleFileSuccess (res, file, fileList) {
      let Data = res
      if (Data.messageType === '0') {
        this.$notify({
          title: '消息',
          message: Data.Message || '操作成功',
          position: 'bottom-right',
          showClose: false,
          type: 'success'
        })
        this.dataError = ''
        // 这里需要返回table 解析后的数据
        this.tableData = Data.result || []
        this.loading = true
        this.getResourceData()
      } else {
        this.dataError = Data.message
        this.$notify.error({
          title: '消息',
          position: 'bottom-right',
          message: this.dataError
        })
      }
    },
    goToRouter (index, item) {
      if (this.templateId !== item.id) {
        this.leftNavIndex = index
        this.templateId = item.id
        this.templateName = item.name
        this.clearSelection()
        this.query()
      }
    },
    getNavData () {
      templateApi.findTemplate('TEMPLATE').then((res) => {
        this.leftNavData = []
        if (res.data.messageCode === '200' && res.data.result) {
          this.leftNavData = res.data.result
          this.templateId = this.leftNavData[0].id
          this.templateName = this.leftNavData[0].name
          this.getResourceData()
        }
      })
    },
    query () {
      this.pageIndex = 1
      this.getResourceData()
    },
    getResourceData () {
      this.loading = true
      resourceApi.findResourcePage({
        name: this.searchForm.name,
        number: this.searchForm.number,
        templateIds: [this.templateId],
        pageSize: this.pageSize,
        pageIndex: this.pageIndex
      }).then((res) => {
        this.loading = false
        let result = res.data.result
        this.$refs.multipleTable.doLayout()
        if (res.data.messageCode === '200' && result) {
          let reData = result.rows
          for (let i = 0; i < reData.length; i++) {
            let row = reData[i]
            if (row.dataJson) {
              let map = eval('(' + row.dataJson + ')')
              if (map) {
                for (let key in map) {
                  row[key] = map[key]
                }
              }
            }
          }
          this.tableData = reData
          this.totalCount = result.totalCount
          let onlyId = this.onlyId
          if (onlyId.length > 0) {
            this.$nextTick(() => {
              this.tableData.forEach((row) => {
                for (let i in onlyId) {
                  let id = onlyId[i]
                  if (row.id === id) {
                    this.$refs.multipleTable.toggleRowSelection(row)
                    break
                  }
                }
              })
            })
          }
        } else {
          this.tableData = []
          this.totalCount = 0
        }
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.tableData = []
      this.getResourceData()
    },
    handleCurrentChange (val) {
      this.pageIndex = val
      this.tableData = []
      this.getResourceData()
    },
    cancel () {
      this.active = '1'
      this.addForm = {}
      this.dataJson = {}
      this.disable = false
      this.dialogFormVisible = false
      this.isReady = false

      this.oneData = [];
      this.twoData = [];
      this.threeData = [];
      this.fourData = [];
      this.$refs.lonRef.initData();
      this.$refs.latRef.initData();
    },
    showDialog (type, row) {
      this.getOne();
      this.dialogFormType = type
      this.dialogFormTitle = this.titleData[type]
      this.addForm.number = type !== 'edit' ? new Date().Format('yyyyMMddhhmmss') : null
      if (row) {
        let oneId = row.oneId
        if (oneId) {
          this.getChildren(oneId).then(res => {
            this.twoData = res
          })
        }
        let twoId = row.twoId
        if (twoId) {
          this.getChildren(twoId).then(res => {
            this.threeData = res
          })
        }
        let threeId = row.threeId
        if (threeId) {
          this.getChildren(threeId).then(res => {
            this.fourData = res
          })
        }
        this.getInfo(row.id)
      }
      this.disable = type === 'read'
      this.dialogFormVisible = true;
      this.isReady = true;
    },
    getInfo (resourceId) {
      this.addForm = {}
      this.dataJson = {}
      resourceApi.getResourceInfo(resourceId).then((res) => {
        let result = res.data.result
        if (res.data.messageCode === '200' && result) {
          this.addForm = result
          this.chilLon = result.lon;
          this.chilLat = result.lat;
          this.isReady = true
          let dataJson = result.dataJson ? JSON.parse(result.dataJson) : {}
          for (let key in dataJson) {
            let value = dataJson[key]
            this.$set(this.dataJson, key, value)
          }
        }
      })
    },
    uploadFile (file) {
      let formData = new FormData()
      formData.append('file', file.file)
      formData.append('folder', 'resource')
      resourceApi.uploadFile(formData).then((res) => {
        if (res.data.messageCode === '200') {
          this.dataJson[file.filename] = res.data.result
        }
      })
    },
    handleExceed (files, fileList) {
      this.$message.warning('只能选择一个文件')
    },
    saveResource () {
      if (!this.addForm.oneId) {
        this.$message({
          message: '请选择保存库',
          type: 'warning'
        })
        return false
      }
      if (!this.addForm.twoId) {
        this.$message({
          message: '请选择保存区',
          type: 'warning'
        })
        return false
      }
      if (!this.addForm.threeId) {
        this.$message({
          message: '请选择隶属大类',
          type: 'warning'
        })
        return false
      }
      if (!this.addForm.fourId) {
        this.$message({
          message: '请选择小区',
          type: 'warning'
        })
        return false
      }
      if (!this.addForm.number) {
        this.$message({
          message: '请输入植株编号',
          type: 'warning'
        })
        return false
      }
      if (!this.addForm.registerSaveId) {
        this.$message({
          message: '请选择种质名称',
          type: 'warning'
        })
        return false
      }
      this.showLoading()
      this.addForm.templateId = this.templateId
      this.addForm.dataJson = this.dataJson ? JSON.stringify(this.dataJson) : null
      resourceApi.saveResource(this.addForm).then((res) => {
        this.hideLoading()
        if (res.data.messageCode === '200') {
          this.$notify({
            title: '消息',
            message: (this.dialogFormTitle + '成功！'),
            position: 'bottom-right',
            showClose: false,
            type: 'success'
          })
          this.getResourceData()
          this.cancel()
        } else {
          this.$notify.error({
            title: '消息',
            message: this.dialogFormTitle + '失败'
          })
        }
      })
    },
    initQrCode (row) {
      this.dialogQrCodeVisible = true
      this.$nextTick(() => {
        this.$refs.qrCodeDiv.innerHTML = ''
        let curl = location.href.split('/#/')[0]
        curl = curl + '/#/code?resourceId=' + row.id
        QRCode.toCanvas(this.$refs.qrCodeDiv, curl, {
          width: 300,
          height: 300,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff' // 二维码背景色
        }, function (error) {
          if (error) console.error(error)
        })
      })
    },
    setFileList (data) {
      let fileList = []
      if (data) {
        let name = data.substring(data.lastIndexOf('/') + 1, data.length)
        fileList.push({name: name, url: this.fileServerUrl + data})
      }
      return fileList
    },
    registerSaveChange (data) {
      if (data) {
        resourceApi.getRegisterPreservationInfo(data).then(res => {
          let result = res.data.result
          if (res.data.message === 'success') {
            this.$set(this.addForm, 'name', result.name)
            this.$set(this.addForm, 'type', result.type)
            this.$set(this.addForm, 'lon', result.lon)
            this.$set(this.addForm, 'lat', result.lat)
            this.$set(this.addForm, 'alt', result.alt)
          }
        })
      }
    },
    showLoading () {
      this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    hideLoading () {
      this.$loading().close()
    },
    initBtn () {
      let permissionBtn = JSON.parse(localStorage.permissionBtn)
      this.addBtn = permissionBtn['survey_add']
      this.updateBtn = permissionBtn['survey_update']
      this.deleteBtn = permissionBtn['survey_delete']
      this.importBtn = permissionBtn['survey_import']
      this.exportBtn = permissionBtn['survey_export']
    },
    showRegister () {
      this.registerPage()
      this.registerVisible = true
    },
    registerPage () {
      let params = {
        name: this.registerName,
        pageIndex: this.registerIndex,
        pageSize: this.registerSize
      }
      resourceApi.findRegisterPreservationPage(params).then(res => {
        let result = res.data.result
        if (res.data.message === 'success' && result) {
          this.registerTotal = result.totalCount
          this.registerData = result.rows
        } else {
          this.registerTotal = 0
          this.registerData = []
        }
      })
    },
    registerPager (val) {
      this.registerIndex = val
      this.registerPage()
    },
    cancelRegister () {
      this.registerName = null
      this.registerIndex = 1
      this.registerTotal = 0
      this.registerData = []
      this.registerVisible = false
    },
    checkedTableRows (row, column, event) {
      this.$set(this.addForm, 'registerSaveId', row.id)
      this.$set(this.addForm, 'name', row.name)
      this.$set(this.addForm, 'type', row.type)
      this.$set(this.addForm, 'lon', row.lon)
      this.$set(this.addForm, 'lat', row.lat)
      this.$set(this.addForm, 'alt', row.alt)

      let oneId = row.oneId;
      if (oneId) {
        this.selectedOne(oneId);
        this.$set(this.addForm, 'oneId', row.oneId);
      }

      let twoId = row.twoId;
      if (twoId) {
        this.selectedTwo(twoId);
        this.$set(this.addForm, 'twoId', row.twoId)
      }

      let threeId = row.threeId;
      if (threeId) {
        this.selectedThree(threeId);
        this.$set(this.addForm, 'threeId', row.threeId);
        this.$set(this.addForm, 'fourId', row.fourId);
      }
      this.cancelRegister()
    },
    beforeUpload (file) {
      let flag = false
      let name = file.name
      if (name.indexOf('.') > -1) {
        let suffix = name.substring(name.lastIndexOf('.') + 1, name.length)
        if (suffix === 'xls' || suffix === 'xlsx') {
          flag = true
        }
      }
      if (!flag) {
        this.$message({
          message: '只能上传xls/xlsx文件',
          type: 'warning'
        })
      } else {
        this.showLoading()
      }
      return flag
    },
    handleSuccess (res, file, fileList) {
      this.hideLoading()
      if (res.message === 'success') {
        this.findPage()
        this.importVisible = false
        this.$message({
          message: '导入成功',
          type: 'success'
        })
      } else {
        let message = res.message
        if (message && message.indexOf(':') > -1) {
          message = message.substring(message.lastIndexOf(':') + 1, message.length)
        }
        this.$message.error(message ? message : '导入失败')
      }
    },
    handleSelect (selection, row) {
      let id = row.id
      let checked = false
      for (let i in selection) {
        let item = selection[i]
        if (item.id === id) {
          checked = true
          break
        }
      }
      if (checked) {
        this.onlyId.push(id)
      } else {
        let index = this.onlyId.indexOf(id)
        this.onlyId.splice(index, 1)
      }
    },
    handleSelectAll (selection) {
      if (selection.length > 0) {
        for (let i in selection) {
          let item = selection[i]
          if (this.onlyId.indexOf(item.id) === -1) {
            this.onlyId.push(item.id)
          }
        }
      } else {
        let data = this.tableData
        for (let i in data) {
          let item = data[i]
          let index = this.onlyId.indexOf(item.id)
          if (index !== -1) {
            this.onlyId.splice(index, 1)
          }
        }
      }
    },
    clearSelection () {
      this.onlyId = []
      this.$refs.multipleTable.clearSelection()
    },
    getWidth (data) {
      let flexWidth = 0
      for (const char of data) {
        if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
          // 如果是英文字符，为字符分配8个单位宽度
          flexWidth += 16
        } else if (char >= '\u4e00' && char <= '\u9fa5') {
          // 如果是中文字符，为字符分配15个单位宽度
          flexWidth += 20
        } else {
          // 其他种类字符，为字符分配8个单位宽度
          flexWidth += 16
        }
      }
      if (flexWidth < 100) {
        // 设置最小宽度
        flexWidth = 100
      }
      return flexWidth
    },
    async exportTmpVal (isAll) {
      if (!isAll) {
        if (this.onlyId.length === 0) {
          this.$message({
            message: '请选择需要导出的数据',
            type: 'warning'
          })
          return false
        }
      }

      let loading = this.$loading({
        lock: true,
        text: '数据导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      let params = {
        isAll: isAll,
        onlyId: this.onlyId,
        templateId: this.templateId,
        name: this.searchForm.name,
        number: this.searchForm.number
      }
      let url = '/gr/resource/exportExcel'
      await resourceApi.downloadExcel(url, params)
      loading.close()
      this.clearSelection()
    },
    deleteRow(row) {
      let tips = ''
      if (row) {
        tips = `此操作将删除: ${row.name}, 是否继续?`
      } else {
        return
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showLoading();
        resourceApi.deleteResource(row.id).then(res => {
          this.hideLoading();
          if (res.data.message === 'success') {
            this.getResourceData();
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            });
          }
        });
      }).catch(() => {});
    },
    deleteBatch() {
      if (this.onlyId.length === 0) {
        this.$message({
          message: '请选择需要删除的数据',
          type: 'warning',
        })
        return false
      }

      let tips = `确定要删除吗?`
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.showLoading();
        resourceApi.deleteResourceBatch({ids: this.onlyId}).then(res => {
          this.hideLoading();
          if (res.data.message === 'success') {
            this.getResourceData();
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            });
          }
        });
      }).catch(() => {});
    }
  },
  watch: {
    templateId (data) {
      templateApi.findColumn(data).then(res => {
        if (res.data.message === 'success') {
          this.dynamicField = res.data.result
        } else {
          this.dynamicField = []
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  height: 100vh;
  display: flex;
  box-sizing: border-box;
}

.leftNaV {
  box-sizing: border-box;
  color: #FFFFFF;
  /*font-size: 2rem;*/
  width: 13%;
  min-width: 240px;
  background: rgba(24, 32, 45, 0.2);
  /*background-color: red;*/
  height: calc(100vh - 190px);
  max-height: calc(100vh - 190px);
  display: flex;
  justify-content: center;
  border: 1px solid rgba(0, 245, 255, 0.5);
  position: relative;
  /*align-items: center;*/

  ul {
    margin-top: 9%;
    width: 80%;
  }

  li {
    cursor: pointer;
    font-size: 2rem;
    text-align: left;
    padding: 15px 15%;
    margin-bottom: 15px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    &.active {
      box-shadow: inset 0 0 15px rgba(0, 245, 255, 1);
    }

    img {
      margin-right: 10px;
    }
  }
}

.rightContent {
  font-size: 2.2rem;
  margin-left: 2%;
  width: calc(100% - 240px - 2%);
  height: calc(100vh - 250px);
}

& /deep/ .el-pagination .el-select .el-input .el-input__inner {
  border: 1px solid #FFFFFF;
}

& /deep/ .el-pagination__editor.el-input .el-input__inner {
  border: 1px solid #FFFFFF;
}

.search {
}

#QRCode {
  display: flex;
  justify-content: center;
}

.sName {
  margin-left: 60px;
  color: #fff;
  font-size: 15px;
}

.avue-crud__pagination {
  margin: 10px 0 0 80%;
}

.p-frame {
  -webkit-appearance: none;
  background-color: transparent;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #FFFFFF;
  color: #FFF;
}

.forms {
  overflow: hidden;
}

table.table-all tr td {
  border: 1px solid #D3D3D3;
}

.table-tr1 {
  height: 35px;
  border-bottom: 1px solid #D3D3D3;
}

.table-tr2 {
  height: 35px;

}

.table-td1 {
  color: #D3D3D3;
  font-weight: bold;
  font-size: 16px;
  padding: 8px 5px 12px 0;
  border-bottom: 1px solid #D3D3D3;
}

.table-td2 {
  width: 20%;
  color: #D3D3D3;
  font-size: 15px;
  padding: 8px 5px 12px 11px;
  border-right: 1px solid #D3D3D3;
}

.table-td3 {
  width: 30%;
  color: #D3D3D3;
  font-size: 15px;
  border-right: 1px solid #D3D3D3;
}
.td3-box {
  display: flex;
  justify-content: space-between;
  line-height: 45px;
  margin-left: 5px;
  margin-right: 5px;
}

.table-td4 {
  width: 19.6%;
  color: #D3D3D3;
  font-size: 15px;
  padding: 8px 5px 12px 11px;
  border-right: 1px solid #D3D3D3;
}

.table-td5 {
  width: 80.4%;
  color: #D3D3D3;
  font-size: 15px;
  border-right: 1px solid #D3D3D3;
}

.td-input {
  width: 100%;
  height: 35px;
  outline: 0;
  border: 0;
  background: 0 0;
}

/deep/ .el-input__inner {
  width: 100%;
  color: #FFFFFF;
  font-size: 1.5rem;
  border: 0;
  background-color: #32f1ff16;
  margin-top: 1px;
}

/deep/ .el-input__icon {
  margin-top: 3px;
}

/deep/ .el-collapse {
  outline: 0;
  border: 0;
}

/deep/ .el-collapse-item__header {
  width: 100%;
  height: 35px;
  line-height: 35px;
  background-color: transparent;
  color: #FFF;
  cursor: pointer;
  border: 0;
}

/deep/ .el-collapse-item__content {
  padding-bottom: 0px;
  font-size: 13px;
  color: #FFF;
  border-bottom: 0;
}

/deep/ .el-collapse-item__wrap {
  background-color: transparent;
  border-bottom: 0;
}

/deep/ .el-collapse-item__header {
  font-size: 16px;
  padding-left: 11px;
  border-bottom: 1px solid #D3D3D3;
  width: 98.9%;
}

/deep/ .el-collapse-item__header.is-active {
  font-size: 16px;
  padding-left: 11px;
}

/deep/ .el-collapse-item__arrow {
  margin-right: 35px;
}

/deep/ .el-collapse-item__arrow.is-active {
  margin-right: 35px;
}

/deep/ .table-select {
  width: 180px;
  height: 35px;
  border: 1px solid #fff;
  background: 0 0;
  color: #D3D3D3;
}

.qr-ul {
  width: 100%;
  display: flex;
  flex-direction: row;
  border: 1px solid #D3D3D3;
}

.dynamic {
  .qr-ul div {
    width: 100%;
    display: flex;
    flex-direction: row;
  }
}

.dialog-footer {
  .paging {
    margin: 0px;
  }
}
.leftImg {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 114px;
  margin-right: 7%;
  overflow: hidden;
}

.import {
  /deep/ .el-dialog__body {
    border-bottom: 1px solid #1f5aab;
  }
}

.exportMenu {
  margin-left: 10px;
}

/deep/ .el-dropdown-menu__item:focus,
.el-dropdown-menu__item:not(.is-disabled):hover {
  color: #ffffff;
  background-color: #32f1ff16;
}
/deep/ .el-table__fixed-right {
  background: #105088;
}
</style>
<style lang="less">
.el-upload-dragger {
  background-color: transparent;
}
</style>
